import subprocess
import sys


def is_frida_running():
    """检查是否有 frida 相关进程正在运行"""
    try:
        result = subprocess.run(
            ['adb', 'shell', 'ps | grep frida'],
            capture_output=True, text=True
        )
        output = result.stdout.strip()
        return bool(output)  # 如果有输出，说明 frida 正在运行
    except Exception as e:
        print(f"检查 Frida 运行状态时出错: {e}")
        return False


def kill_frida_processes():
    """查找并杀掉所有 frida 相关的进程"""
    try:
        result = subprocess.run(
            ['adb', 'shell', 'ps | grep frida'],
            capture_output=True, text=True, timeout=10
        )
        output = result.stdout.strip()
        if output:
            lines = output.splitlines()
            for line in lines:
                pid = line.split()[1]
                kill_command = f'adb shell "su -c \'kill -9 {pid}\'"'
                subprocess.run(kill_command, shell=True, check=True, timeout=5)
                print(f"Frida 进程 {pid} 已被杀掉")
            print("所有 Frida 相关进程已杀掉。")
        else:
            print("没有找到任何 Frida 相关的进程。")
    except subprocess.TimeoutExpired:
        print("杀掉 Frida 进程时超时")
    except Exception as e:
        print(f"杀掉 Frida 进程时出错: {e}")


def start_frida_server():
    """检查并启动 frida-server"""
    if is_frida_running():
        print("检测到 frida 相关进程，正在杀掉...")
        kill_frida_processes()
    try:
        print("正在后台启动 Frida-server...")
        # 使用 Popen 在后台启动 frida-server
        start_frida_command = 'adb shell "su -c \'./data/local/tmp/frida-server-16.5.5-android-x86_64 &\'"'
        process = subprocess.Popen(start_frida_command, shell=True)
        print("Frida-server 已在后台启动！")
    except Exception as e:
        print(f"启动 Frida-server 时出错: {e}")


if __name__ == "__main__":
    start_frida_server()
